from flask import Flask
from flask import abort, redirect, render_template, request, send_file, url_for
import imghdr
import os


app = Flask(__name__)


@app.route("/", redirect_to="/html/")
def index():
    return "hello world!"


@app.route("/favicon.ico")
def favicon():
    return redirect(url_for("static", filename="favicon.png"))


@app.route("/html/")
@app.route("/html/<path:name>")
def default(name=""):
    root_path = "html/" + name
    if os.path.isfile(root_path):
        return send_file(root_path)

    if os.path.isfile(root_path + "/index.html"):
        return send_file(root_path + "/index.html")

    file_list = sorted([file + "/" for file in os.listdir(root_path) if os.path.isdir(root_path + "/" + file)])
    return render_template("list.html", cols=3, file_list=file_list, centered=True)


@app.route("/comic/")
def comic_index():
    file_list = sorted([file + "/" for file in os.listdir("comic") if os.path.isdir("comic/" + file)])
    return render_template("list.html", cols=5, file_list=file_list, centered=True, title="漫画")


@app.route("/comic/<path:file>")
def comic_child(file=""):
    file_path = ("comic/" + file).rstrip("/")
    if os.path.isfile(file_path):
        return send_file(file_path)

    table_path = "/".join(file_path.split("/")[:-1]) + "/"
    child_path = file_path + "/"
    current = file_path.split("/")[-1]

    print(table_path)
    table_list = sorted([file for file in os.listdir(table_path) if os.path.isdir(table_path + file)])
    print(table_list)

    child_list = []
    image_list = []
    for file in os.listdir(child_path):
        if os.path.isdir(child_path + file):
            child_list.append(file)
        elif os.path.isfile(child_path + file) and imghdr.what(child_path + file):
            image_list.append(file)

    if image_list:
        image_list = sorted(image_list)
        child_list = None
    else:
        image_list = None
        child_list = sorted(child_list)
    return render_template(
        "comic.html",
        table_path=table_path,
        table_list=table_list,
        current=current,
        child_path=child_path,
        image_list=image_list,
        child_list=child_list,
    )


@app.route("/<string:root>/")
def table(root=""):
    name_list = {"books": "书库", "share": "网盘"}
    root += "/"
    file_list = sorted([file for file in os.listdir(root) if os.path.isfile(root + file)])
    return render_template("list.html", cols=5, file_list=file_list, title=name_list.get(root))


@app.route("/<string:root>/<path:file>")
def files(root="", file=""):
    file_path = root + "/" + file
    if os.path.isfile(file_path):
        return send_file(file_path)
    else:
        abort(404)


if __name__ == "__main__":
    app.run()
